<?php
/**
 * websocket服务开启事件
 */
namespace app\Listener;

use Co;
use Swostar\Event\Listener;

class StartListener extends Listener
{
    protected $name = 'start';

    public function run()
    {
        /** 
         * 通过协程，在服务器启动时，发送本机信息到路由服务器，注册到路由服务器
        */
        go(function () {
            $config = app('config')->get('server');
            
            $cli = new \Swoole\Coroutine\Http\Client($config['routeServer']['host'], $config['routeServer']['port']);
            // 升级为长连接
            if($cli->upgrade('/')) {
                $data = [
                    'ip' => $config['localhost'],
                    'port' => $config['websocket']['port'],
                    'serverName' => $config['serverName'],
                    'method' => 'register',
                ];

                $cli->push(json_encode($data));
                swoole_timer_tick(3000, function() use ($cli) {
                    $cli->push('{"aaa":"aaa"}');  // 发送ping包，保持连接
                });
            }
        });
    }

}
